package com.example.travel.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 上传图片工具类
 */
@RestController
public class UploadUtil {

    @Autowired
    private OssUtil ossUtil;

    /**
     * 上传图片文件到oss
     */
    public String upload(MultipartFile file) throws IOException {
        // 生成唯一的字符串
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String originalFilename = file.getOriginalFilename();
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        fileName += suffixName;
        File newFile = new File(fileName);
        FileOutputStream os = new FileOutputStream(newFile);
        os.write(file.getBytes());
        os.close();
        file.transferTo(newFile);
        return ossUtil.upload(newFile,fileName);
    }

}
